let app = getApp();
const util = require('../../util/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: 1,
    invalidTitle: "提示",
    invalidArea: "请确保您已到达巡检地点！",
    item: []
  },
  onLoad(options) {
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem2/getSchoolUUIDS',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        schoolId: parseInt(app.globalData.departmentId)
      }),
      dataType: 'json',
      success: res => {
        this.setData({
          uuids: res.data.uuids.split(",")
        })
      }
    })
    let item = dd.getStorageSync({ key: 'inspItemList' })
    this.setData({
      item: item.data
    })
  },

  onShow: function () {
    let item = this.data.item;
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem2/getInspectPlanStatusByInspectPlanId',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        inspectPlanId: item.inspectPlanId.join(","),
        schoolId: app.globalData.departmentId
      }),
      dataType: 'json',
      success: res => {
        console.log(res.data)
        res.data.sort(function (a, b) {
          return a.checked - b.checked
        })
        this.setData({
          ["item.idAndName"]: res.data
        })
      },
      complete: () => {
        this.setData({
          loading: 0
        })
      }
    })
  },

  showEvent: function (e) {
    let item = this.data.item,
      uncheckedNum = 0,
      checkedNum = 0,
      selectCheck = null
    for (let i = 0; i < item.idAndName.length; i++) {
      if (item.idAndName[i].checked == 0) {
        uncheckedNum++;
      } else {
        checkedNum++;
      }
    }
    if (e.currentTarget.dataset.checked == 0) {
      selectCheck = checkedNum
    } else if (e.currentTarget.dataset.checked == 1) {
      selectCheck = uncheckedNum
    }
    let obj = {
      select: selectCheck,
      showChecked: e.currentTarget.dataset.checked
    }
    Object.assign(item, obj)
    this.setData({
      item: item
    })
  },

  bindWorkDetail: util.throttle(function (e) {
    console.log("e============", e.currentTarget.dataset)
    let that = this
    if (e.currentTarget.dataset.checked == 0) {
      // dd.navigateTo({
      //   url: '/page/workInspectDetail/workInspectDetail?inspectPlanId=' + e.currentTarget.dataset.inspectplanid + '&categoryId=' + e.currentTarget.dataset.categoryid + '&checked=' + e.currentTarget.dataset.checked
      // })
      that.setData({
        fromIndex: 0
      })
      if (e.currentTarget.dataset.macaddress.indexOf("00000") > -1) {
        console.log("无蓝牙模式")
        dd.navigateTo({
          url: `/page/workInspectDetail/workInspectDetail?inspectPlanId=${e.currentTarget.dataset.inspectplanid}&categoryId=${e.currentTarget.dataset.categoryid}&checked=${e.currentTarget.dataset.checked}&address=${e.currentTarget.dataset.address}&className=${e.currentTarget.dataset.classname}&categoryName=${e.currentTarget.dataset.categoryname}`
        })
      } else {
        if (dd.openBluetoothAdapter) {
          
          dd.showLoading({
            content: '正在搜索设备'
          })
          dd.openBluetoothAdapter({

            //开启蓝牙
            fail: (res) => {
              dd.showToast({
                content: '请开启蓝牙',
                duration: 2000
              })
              setTimeout(function () {
                dd.hideLoading()
              }, 2000)
            },

            success(res) {
              console.log("初始化成功")
              dd.startBeaconDiscovery({
                uuids: that.data.uuids,
                success: (res) => {
                  let search = 0
                  function doSearch() {
                    search++
                    console.log(search)
                    if (!that.data.stop) {
                      if (search > 5) {
                        that.showModalOwn()
                      } else {
                        setTimeout(doSearch, 900)
                      }
                    }
                  }
                  doSearch()

                  dd.onBeaconUpdate(function (res) {
                    let blueTooth = e.currentTarget.dataset.macaddress.split(",")
                    console.log("blueTooth", blueTooth)
                    console.log("onBeaconUpdate", res)
                    //加判断条件
                    if (search <= 5) {
                      for (let i = 0; i < res.beacons.length; i++) {
                        let find = 0
                        for (let j = 0; j < blueTooth.length; j++) {
                          if (blueTooth[j].split(":")[0] == res.beacons[i].major && blueTooth[j].split(":")[1] == res.beacons[i].minor) {
                            find = 1
                            break
                          }
                        }

                        if (find == 1) {
                          console.log("找到了")
                          that.setData({
                            stop: 1,
                            bleConnect: 1
                          })
                          dd.hideLoading()
                          dd.offBeaconUpdate()
                          dd.stopBeaconDiscovery()
                          // util.throttle(()=>{
                          dd.navigateTo({
                            url: `/page/workInspectDetail/workInspectDetail?inspectPlanId=${e.currentTarget.dataset.inspectplanid}&categoryId=${e.currentTarget.dataset.categoryid}&checked=${e.currentTarget.dataset.checked}&address=${e.currentTarget.dataset.address}&className=${e.currentTarget.dataset.classname}&categoryName=${e.currentTarget.dataset.categoryname}`
                          })
                          that.setData({
                            fromIndex: 0
                          })
                          // })
                          return
                        }
                      }
                    }
                  })
                },
                fail: (res) => {
                  that.showModalOwn()
                }
              });
              // dd.getBluetoothAdapterState({
              //   success(res) {
              //     console.log("本机蓝牙状态", res)
              //   },
              //   fail(res) {
              //     console.log("")
              //   }
              // })
              // console.log("获取蓝牙成功")
              // //获取当前用户的地理位置信息
              // dd.getLocation({
              //   type: 1,
              //   fail: (res) => {
              //     //不允许打开定位
              //     dd.hideLoading()
              //     //开启系统设置定位
              //     dd.getSystemInfo({
              //       success: (res) => {
              //         if (res.platform == "ios") {
              //           that.setData({
              //             locationContent: '请在系统设置-微信里开启允许微信使用地理位置的开关'
              //           })
              //         }
              //         dd.alert({
              //           title: '未使用地理位置',
              //           content: that.data.locationContent
              //         })
              //       },
              //       fail() {
              //         dd.alert({
              //           title: '未使用地理位置信息',
              //           content: that.data.locationContent
              //         })
              //       }
              //     })
              //   },
              //   success: (res) => {
              //     //允许打开定位
              //     console.log(res)
              //     //搜索蓝牙设备
              //     dd.getBluetoothAdapterState({
              //       success: (res) => {
              //         let available = res.available
              //         let discovering = res.discovering

              //         if (!discovering) {
              //           dd.startBluetoothDevicesDiscovery({
              //             services: [],
              //             //services: [],
              //             success: (res) => {
              //               dd.hideLoading()
              //               dd.onBluetoothDeviceFound((res) => {
              //                 console.log("res-----", res)
              //                 res.devices.forEach(device => {
              //                   if ("D1:A2:BF:A3:0A:CE" == device.deviceId) {
              //                     dd.navigateTo({
              //                       url: '/page/workInspectDetail/workInspectDetail?inspectPlanId=' + e.currentTarget.dataset.inspectplanid + '&categoryId=' + e.currentTarget.dataset.categoryid + '&checked=' + e.currentTarget.dataset.checked
              //                     })
              //                   } else {
              //                     dd.alert({
              //                       content: '未搜索到附近蓝牙'
              //                     })
              //                   }
              //                 })
              //               })
              //               console.log("成功搜索到蓝牙", res)
              //             }
              //           })
              //         }
              //       },
              //       fail: (res) => {
              //         console.log("获取蓝牙状态失败")
              //       }
              //     })
              //     // dd.startBluetoothDevicesDiscovery({
              //     //   services: that.data.uuids,
              //     //   success: (res) => {
              //     //     console.log("成功搜索到蓝牙", res)
              //     //   }
              //     // })

              //     //获得所有已发现的蓝牙设备
              //     dd.getBluetoothDevices({
              //       success: (res) => {
              //         console.log("获得所有已发现的蓝牙设备", res)
              //         for (var i = 0; i < res.devices.length; i++) {
              //           console.log("蓝牙个数： ", i)
              //         }
              //       }
              //     })


              //     dd.getConnectedBluetoothDevices({
              //       services: [],
              //       success: (res) => {
              //         console.log("得到连接的蓝牙设备列表： ", res)
              //       }
              //     })
              //   }
              // })
            }
          })

          //不需要蓝牙
          // console.log("no blu")
          //     dd.navigateTo({
          //       url: `/page/workInspectDetail/workInspectDetail?inspectPlanId=${e.currentTarget.dataset.inspectplanid}&categoryId=${e.currentTarget.dataset.categoryid}&checked=${e.currentTarget.dataset.checked}&address=${e.currentTarget.dataset.address}&className=${e.currentTarget.dataset.classname}`
          //     })
          //     that.setData({
          //       fromIndex: 0
          //     })
          //  } 
          // } else {
          //   dd.navigateTo({
          //     url: '/page/workInspectHistory/workInspectHistory?inspectPlanId=' + e.currentTarget.dataset.inspectplanid + '&categoryId=' + e.currentTarget.dataset.categoryid + '&checked=' + e.currentTarget.dataset.checked
          //   })
          // that.setData({
          //   fromIndex: 0
          // })
        }

      }


    } else {
      dd.navigateTo({
        url: '/page/workInspectHistory/workInspectHistory?inspectPlanId=' + e.currentTarget.dataset.inspectplanid + '&categoryId=' + e.currentTarget.dataset.categoryid + '&checked=' + e.currentTarget.dataset.checked
      })
      that.setData({
        fromIndex: 0
      })
    }
  }),

  onHide: function () {
    this.setData({
      stop: 1
    })
    dd.stopBluetoothDevicesDiscovery()
    dd.closeBluetoothAdapter()
  },


  onUnload: function () {
    this.setData({
      stop: 1
    })
    dd.stopBluetoothDevicesDiscovery()
    dd.closeBluetoothAdapter()
  },


  showModalOwn: function () {
    let that = this
    dd.hideLoading()
    dd.offBeaconUpdate()
    dd.stopBeaconDiscovery()
    dd.showToast({
      type: 'fail',
      content: that.data.invalidArea,
      duration: 3000
    })
  }

});
